﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management.Automation;

namespace AppFabricAdministrator
{
    public partial class CacheConfigUI : UserControl
    {
        private string exportCmdTmplt = "Export-CacheClusterConfig -File \"{0}\"";
        private string importCmdTmplt = "Import-CacheClusterConfig -File \"{0}\" -Confirm -Force";
        private string stopClusterCmd = "Stop-CacheCluster";

        public CacheConfigUI()
        {
            InitializeComponent();
        }

        private void btnSaveDialog_Click(object sender, EventArgs e)
        {
            this.saveCacheConfig.Filter = "Configuration File|*.config|Xml File|*.xml|All Files|*.*";
            var extnFilters = "config,xml,";
            var filters = extnFilters.Split(',');
            var res = this.saveCacheConfig.ShowDialog();
            if (res.Equals(DialogResult.OK))
            {
                var fn = this.saveCacheConfig.FileName;
                this.tb_exportConfig.Text = fn;
            }
        }

        private void btnOpenDialog_Click(object sender, EventArgs e)
        {
            var res = this.openCacheConfig.ShowDialog();
            if (res.Equals(DialogResult.OK))
            {
                this.tb_importedConfig.Text = this.openCacheConfig.FileName;
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tb_exportConfig.Text))
            {
                var exportCmd = string.Format(exportCmdTmplt, tb_exportConfig.Text);
                bool isSuccess = false;
                var resultString = ScriptHelper.RunScript(exportCmd, "Successfully exported config.", ExportConfig, out isSuccess);
                //AppfabricAdministrator.tbScriptOut.Text = resultString;
                if (isSuccess)
                    MessageBox.Show("Successfully exported config.");
            }
        }

        public string ExportConfig(IEnumerable<PSObject> results)
        {
            return string.Empty;
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tb_importedConfig.Text))
            {
                var importCmd = string.Format(importCmdTmplt, tb_importedConfig.Text);
                bool isSuccess = false;
                ScriptHelper.RunScript(stopClusterCmd, "", null, out isSuccess);
                ScriptHelper.RunScript(importCmd, "Successfully imported config.", ImportConfig, out isSuccess);

            }
        }

        public string ImportConfig(IEnumerable<PSObject> results)
        {
            return string.Empty;
        }
    }
}
